package com.xjy.web.controller.system;

import cn.hutool.core.util.StrUtil;
import com.xjy.common.annotation.Log;
import com.xjy.common.constant.UserConstants;
import com.xjy.common.core.controller.BaseController;
import com.xjy.common.core.domain.AjaxResult;
import com.xjy.common.core.domain.entity.SysBudget;
import com.xjy.common.core.domain.entity.SysDept;
import com.xjy.common.enums.BusinessType;
import com.xjy.common.exception.UtilException;
import com.xjy.common.utils.SecurityUtils;
import com.xjy.system.service.ISysBudgetService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * 预算科目信息Controller
 *
 * @author xjy
 * @date 2022-02-07
 */
@Api(value = "预算科目信息控制器", tags = {"预算科目信息管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/system/budget")
public class SysBudgetController extends BaseController {
	@Autowired
	private ISysBudgetService iSysBudgetService;
	@ApiOperation("查询预算科目信息列表")
	@PreAuthorize("@ss.hasPermi('system:budget:list')")
	@GetMapping("/list")
	public AjaxResult list(SysBudget sysBudget){
		List<SysBudget> list = iSysBudgetService.selectBudgetList(sysBudget);
		return AjaxResult.success(list);
	}

	/**
	 * 获取预算科目信息详细信息
	 */
	@ApiOperation("获取预算科目信息详细信息")
	@PreAuthorize("@ss.hasPermi('system:budget:query')")
	@GetMapping("/{id}")
	public AjaxResult getinfo(@PathVariable Long id ) {
		return AjaxResult.success(iSysBudgetService.getByIdInfo(id));
	}
	/**
	 * 查询科目列表（排除节点）
	 */
	@ApiOperation("查询科目列表（排除节点）")
	@PreAuthorize("@ss.hasPermi('system:budget:list')")
	@GetMapping("/list/exclude/{id}")
	public AjaxResult excludeChild(@PathVariable(value = "id", required = false) Long id) {
		List<SysBudget> list = iSysBudgetService.selectBudgetList( new SysBudget());
		Iterator<SysBudget> it = list.iterator();
		while (it.hasNext())
		{
			SysBudget d = (SysBudget) it.next();
			if (d.getId().intValue() == id
				|| ArrayUtils.contains(StrUtil.splitToArray(d.getAncestors(), ","), id + ""))
			{
				it.remove();
			}
		}
		return AjaxResult.success(list);
	}
   /**
	* 获取科目预算下拉数列表
	* */
   @GetMapping("/treeselect")
   public AjaxResult treeselect(SysBudget sysBudget) {
	   sysBudget.setAuditStatus(true);
	   sysBudget.setStatus("0");
	   List<SysBudget> list = iSysBudgetService.selectBudgetList(sysBudget);
	   return AjaxResult.success(iSysBudgetService.treeselectList(list));
   }
  /**
   * 新增预算科目
   * */
	@ApiOperation("新增预算科目信息")
	@PreAuthorize("@ss.hasPermi('system:budget:add')")
	@Log(title = "预算科目信息", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody SysBudget sysBudget) {
		if (UserConstants.NOT_UNIQUE.equals(iSysBudgetService.checkDeptNameUnique(sysBudget)))
		{
			return AjaxResult.error("新增科目'" + sysBudget.getSubjectName() + "'失败，科目名称已存在");
		}
		sysBudget.setCreateBy(SecurityUtils.getUsername());
		return toAjax(iSysBudgetService.insertBudget(sysBudget));
	}


	/**
	 * 修改预算科目
	 * */
	@ApiOperation("修改预算科目信息")
	@PreAuthorize("@ss.hasPermi('system:budget:edit')")
	@Log(title = "预算科目信息", businessType = BusinessType.UPDATE)
	@PutMapping("/edit")
	public AjaxResult edit(@RequestBody SysBudget sysBudget) {
		if (UserConstants.NOT_UNIQUE.equals(iSysBudgetService.checkDeptNameUnique(sysBudget)))
		{
			return AjaxResult.error("修改科目'" + sysBudget.getSubjectName() + "'失败，科目名称已存在");
		}
		else if (sysBudget.getParentNo().equals(sysBudget.getId()))
		{
			return AjaxResult.error("修改科目'" + sysBudget.getSubjectName() + "'失败，上级科目不能是自己");
		}
		else if (StrUtil.equals(UserConstants.BUDGET_DISABLE, sysBudget.getStatus())
			&& iSysBudgetService.selectNormalChildrenDeptById(sysBudget.getId()) > 0)
		{
			return AjaxResult.error("该科目包含未停用的子科目！");
		}
		sysBudget.setUpdateBy(SecurityUtils.getUsername());
		return toAjax(iSysBudgetService.updateBudget(sysBudget));
	}


	/**
	 * 修改预算科目
	 * */
	@ApiOperation("修改预算科目信息")
	@PreAuthorize("@ss.hasPermi('system:budget:edit')")
	@Log(title = "预算科目信息", businessType = BusinessType.UPDATE)
	@PutMapping("/audit")
	public AjaxResult audit(@RequestBody SysBudget sysBudget) {
		SysBudget sb = iSysBudgetService.getByIdInfo(sysBudget.getId());
		if(sb.getAuditStatus()){
			throw new UtilException("该数据无需重新审批！");

		}
		sysBudget.setAuditStatus(true);

		return this.edit(sysBudget);
	}

	/**
	 * 删除科目
	 */
	@PreAuthorize("@ss.hasPermi('system:dept:remove')")
	@Log(title = "科目管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{Id}")
	public AjaxResult remove(@PathVariable Long Id) {
		if (iSysBudgetService.hasChildByDeptId(Id))
		{
			return AjaxResult.error("存在下级科目,不允许删除");
		}
		return toAjax(iSysBudgetService.deletebudgetById(Id));
	}

	/**
	 * 加载对应角色科目树
	 */
	@GetMapping(value = "/roleBudgetTreeselect/{roleId}")
	public AjaxResult roleBudgetTreeselect(@PathVariable("roleId") Long roleId)
	{
		List<SysBudget> depts = iSysBudgetService.selectBudgetList(new SysBudget());
		Map<String,Object> ajax = new HashMap<>();
		ajax.put("checkedKeys", iSysBudgetService.selectBudgetListByRoleId(roleId));
		ajax.put("depts", iSysBudgetService.buildBudgetTreeSelect(depts));
		return AjaxResult.success(ajax);
	}
	}

